package com.futvan.z.framework.util;

import com.futvan.z.framework.core.JobsListener;
import com.futvan.z.framework.core.z;
import com.futvan.z.system.zjob.z_job;
import org.quartz.*;
import org.quartz.impl.matchers.KeyMatcher;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JobUtil {


	/**
	 * 添加任务
	 * @param <T>
	 * @return
	 * @throws Exception 
	 * @throws Exception 
	 */

	public static void jobAdd(z_job job) throws Exception{
		if(z.isNotNull(job.getJobtime())) {
			if("1".equals(job.getJobtype()) && z.isNotNull(job.getEtlid())) {
				//数据抽取与推送任务
				Map<String,String> map = new HashMap<String, String>();
				map.put("etlid", job.getEtlid());
				jobAdd(job.getZid(),job.getJobname(),"com.futvan.z.framework.core.EtlJob",job.getJobtime(),map,job);
			}
			if("0".equals(job.getJobtype())) {
				//自定义任务
				jobAdd(job.getZid(),job.getJobname(),job.getJobclass(),job.getJobtime(),null,job);
			}
		}else {
			z.Error("无效任务："+job.getJobname()+"该任务已启动，但未定义任务执行时间，无法完成任务执行！");
		}


	}

	/**
	 * 运行任务(立即执行)
	 * @return
	 * @throws Exception 
	 * @throws Exception 
	 */
	public static void jobRun(z_job job) throws Exception{
		if(z.isNotNull(job.getJobtime())) {
			if("1".equals(job.getJobtype()) && z.isNotNull(job.getEtlid())) {
				//数据抽取与推送任务
				Map<String,String> map = new HashMap<String, String>();
				map.put("etlid", job.getEtlid());
				jobRun(job.getZid(),"com.futvan.z.framework.core.EtlJob",map,job);
			}
			if("0".equals(job.getJobtype())) {
				//自定义任务
				jobRun(job.getZid(),job.getJobclass(),null,job);
			}
		}else {
			z.Error("无效任务："+job.getJobname()+"该任务已启动，但未定义任务执行时间，无法完成任务执行！");
		}
	}

	public static void jobRun(String JobId,String JobClass,Map parameter,z_job zjob) throws Exception{
		String tempNum = z.newNumber();
		@SuppressWarnings("unchecked")
		JobDetail job = JobBuilder.newJob((Class<? extends Job>) Class.forName(JobClass)).withIdentity(JobId+tempNum, JobId+"-Detail-Group").build();

		//添加参数
		if(z.isNotNull(parameter)) {
			job.getJobDataMap().putAll(parameter);
		}
		
		//创建监听器
		JobsListener jl = new JobsListener(zjob);
		KeyMatcher<JobKey> keyMatcher = KeyMatcher.keyEquals(job.getKey());
		z.job.getListenerManager().addJobListener(jl, keyMatcher);

		//创建执行时间
		Trigger trigger =  TriggerBuilder.newTrigger().withIdentity(JobId+tempNum+"-Now-Trigger" , JobId+tempNum+"-Now-Trigger-Group").withSchedule(SimpleScheduleBuilder.simpleSchedule()).startAt(new Date()).build();

		//添加job
		z.job.scheduleJob(job, trigger);
	}

	public static void jobAdd(String JobId,String JobName,String JobClass,String CronExpression,Map parameter,z_job zjob) throws Exception{
		//创建任务
		@SuppressWarnings("unchecked")
		JobDetail job = JobBuilder.newJob((Class<? extends Job>) Class.forName(JobClass)).withIdentity(JobId, JobId+"-Detail-Group").build();

		//添加参数
		if(z.isNotNull(parameter)) {
			job.getJobDataMap().putAll(parameter);
		}

		//创建监听器
		JobsListener jl = new JobsListener(zjob);
		KeyMatcher<JobKey> keyMatcher = KeyMatcher.keyEquals(job.getKey());
		z.job.getListenerManager().addJobListener(jl, keyMatcher);

		//生成触发器
		TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger().withIdentity(JobId+"-Trigger", JobId+"-Trigger-Group").startNow();
		//触发器时间设定  
		triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(CronExpression));
		CronTrigger trigger = (CronTrigger) triggerBuilder.build();

		//添加任务工厂
		z.job.scheduleJob(job, trigger);

		//添加运行记录
		HashMap<String,String> jobMap = new HashMap<String,String>();
		jobMap.put("name", JobName);
		jobMap.put("CronExpression", CronExpression);
		jobMap.put("parameter", JsonUtil.getJson(parameter));
		z.jobRunList.put(JobId, jobMap);
	}

	/**
	 * 删除任务
	 * @param JobId
	 * @return
	 */
	public static void jobDelete(String JobId) throws Exception{
		TriggerKey triggerKey = TriggerKey.triggerKey(JobId+"-Trigger",JobId+"-Trigger-Group");
		// 停止触发器
		z.job.pauseTrigger(triggerKey);
		// 移除触发器
		z.job.unscheduleJob(triggerKey);
		// 删除任务
		z.job.deleteJob(JobKey.jobKey(JobId,JobId+"-Detail-Group"));
		//删除记录
		z.jobRunList.remove(JobId);
	}


}
